package com.example.text.service.impl;

import com.example.text.entity.User;
import com.example.text.repository.ApiaccountRepository;
import com.example.text.service.ApiaccountService;
import com.example.text.utils.JsonResult;
import com.example.text.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class ApiaccountServiceImpl implements ApiaccountService {

    private final ApiaccountRepository userRepository;
    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public ApiaccountServiceImpl(ApiaccountRepository userRepository,
                                 RedisTemplate<String, String> redisTemplate) {
        this.userRepository = userRepository;
        this.redisTemplate = redisTemplate;
    }

    private String encodePassword(String password) {
        return com.example.text.utils.Md5Utils.encrypt(password);
    }

    private boolean matchesPassword(String rawPassword, String encodedPassword) {
        return encodePassword(rawPassword).equals(encodedPassword);
    }

    private static final String SMS_CODE_PREFIX = "sms:code:";
    private static final long SMS_CODE_EXPIRE_SECONDS = 60;

    @Override
    public JsonResult sendSMSCode(String phone) {
        try {
            if (!Tool.isMobile(phone)) {
                return JsonResult.failed("手机号格式不正确");
            }

            String code = generateSMSCode();
            String key = SMS_CODE_PREFIX + phone;
            redisTemplate.opsForValue().set(key, code, SMS_CODE_EXPIRE_SECONDS, TimeUnit.SECONDS);

            // 使用 System.out 作为临时日志
            System.out.println("发送验证码 " + code + " 到手机号 " + phone);

            return JsonResult.success("验证码发送成功", null);
        } catch (Exception e) {
            System.out.println("发送验证码失败: " + e.getMessage());
            return JsonResult.failed("验证码发送失败");
        }
    }

    @Override
    public JsonResult register(String username, String phone, String password, String smsCode) {
        try {
            if (!Tool.isMobile(phone)) {
                return JsonResult.failed("手机号格式不正确");
            }

            if (!Tool.isPassword(password)) {
                return JsonResult.failed("密码必须至少8位且包含非数字字符");
            }

            if (!verifySMSCode(phone, smsCode)) {
                return JsonResult.failed("验证码错误或已过期");
            }

            if (userRepository.existsByUsername(username)) {
                return JsonResult.failed("用户名已存在");
            }

            if (userRepository.existsByPhone(phone)) {
                return JsonResult.failed("手机号已注册");
            }

            User user = new User();
            user.setUsername(username);
            user.setPhone(phone);
            user.setPasswordHash(encodePassword(password));

            userRepository.save(user);
            System.out.println("用户注册成功: username=" + username + ", phone=" + phone);

            return JsonResult.success("注册成功", null);
        } catch (Exception e) {
            System.out.println("注册失败: " + e.getMessage());
            return JsonResult.failed("注册失败: " + e.getMessage());
        }
    }

    @Override
    public JsonResult login(String account, String password) {
        try {
            if (account == null || account.trim().isEmpty()) {
                return JsonResult.failed("账号不能为空");
            }

            Optional<User> userOpt = userRepository.findByUsernameOrPhone(account);
            if (userOpt.isEmpty()) {
                return JsonResult.failed("账号或密码错误");
            }

            User user = userOpt.get();

            if (!matchesPassword(password, user.getPasswordHash())) {
                return JsonResult.failed("账号或密码错误");
            }

            System.out.println("用户登录成功: username=" + user.getUsername());
            return JsonResult.success("登录成功", user.getUsername());
        } catch (Exception e) {
            System.out.println("登录失败: " + e.getMessage());
            return JsonResult.failed("登录失败");
        }
    }

    @Override
    public boolean verifySMSCode(String phone, String code) {
        String key = SMS_CODE_PREFIX + phone;
        String storedCode = redisTemplate.opsForValue().get(key);

        if (code.equals(storedCode)) {
            redisTemplate.delete(key);
            return true;
        }
        return false;
    }

    private String generateSMSCode() {
        int code = (int) ((Math.random() * 9 + 1) * 1000);
        return String.valueOf(code);
    }

}